yjx.service('uploader',['$rootScope','$timeout','ipCookie','$fetch','modalService',function($rootScope,$timeout,ipCookie,$fetch,modalService){
    return{
        // 上传图片到阿里云OSS, url 是需要签名的后端服务地址。 previewId:上传成功后页面展示图片的元素
        uploadimgtooss:   function (url,previewId,btnId){
            var accessid = '',
                accesskey = '',
                host = '',
                policyBase64 = '',
                signature = '',
                callbackbody = '',
                filename = '',
                key = '',
                expire = 0,
                g_object_name = '',
                g_object_name_type = '',
                now = Date.parse(new Date()) / 1000;
            function send_request(){
                var xmlhttp = null;
                if(window.XMLHttpRequest) {
                    xmlhttp=new XMLHttpRequest();
                }else if(window.ActiveXObject){
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                if(xmlhttp!=null){
                    var serverUrl = url;
                    xmlhttp.open( "POST", serverUrl, false );
                    xmlhttp.send( null );
                    return xmlhttp.responseText
                }else{
                    //alert("Your browser does not support XMLHTTP.");
                }
            }

            function check_object_radio(){
                var tt = document.getElementsByName('myradio');
                for (var i = 0; i < tt.length ; i++ ){
                    if(tt[i].checked){
                        g_object_name_type = tt[i].value;
                        break;
                    }
                }
            }

            function get_signature(){
                //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
                now = Date.parse(new Date()) / 1000;
                if(expire < now + 3){
                    var body = send_request();
                    var obj = eval ("(" + body + ")");
                    host = obj.data['host'];
                    policyBase64 = obj.data['policy'];
                    accessid = obj.data['accessid'];
                    signature = obj.data['signature'];
                    expire = parseInt(obj.data['expire']);
                    callbackbody = obj.data['callback'];
                    key = obj.data['dir'];
                    return true;
                }
                return false;
            }

            function random_string(len){
                len = len || 32;
                var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                var maxPos = chars.length;
                var pwd = '';
                for(var i = 0; i < len; i++){
                    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
                }
                return pwd;
            }

            function get_suffix(filename) {
                var pos = filename.lastIndexOf('.');
                var suffix = '';
                if (pos != -1) {
                    suffix = filename.substring(pos);
                }
                return suffix;
            }

            function calculate_object_name(filename) {
                if (g_object_name_type == 'local_name') {
                    g_object_name += "${filename}";
                } else if (g_object_name_type == 'random_name') {
                    var suffix = get_suffix(filename);
                    g_object_name = key + random_string(10) + suffix;
                }
                return '';
            }

            function get_uploaded_object_name(filename) {
                if (g_object_name_type == 'local_name') {
                    var tmp_name = g_object_name;
                    tmp_name = tmp_name.replace("${filename}", filename);
                    return tmp_name;
                } else if(g_object_name_type == 'random_name') {
                    return g_object_name;
                }
            }

            function set_upload_param(up, filename, ret) {
                if (ret == false) {
                    ret = get_signature();
                }
                g_object_name = key;
                if (filename != '') {
                    var suffix = get_suffix(filename);
                    calculate_object_name(filename);
                }
                var new_multipart_params = {
                    'key' : g_object_name,
                    'policy': policyBase64,
                    'OSSAccessKeyId': accessid,
                    'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                    'callback' : callbackbody,
                    'signature': signature
                };

                up.setOption({
                    'url': host,
                    'multipart_params': new_multipart_params
                });

                up.start();
            }

            var uploader = new plupload.Uploader({
                runtimes : 'html5,flash,silverlight,html4',
                browse_button : btnId?btnId:'selectfiles',
                multi_selection: previewId=='#avatar'?false:true,
                container: document.getElementById('container'),
                flash_swf_url : 'common/libs/upload/Moxie.swf',
                silverlight_xap_url : 'common/libs/upload/Moxie.xap',
                url : 'http://oss.aliyuncs.com',

                filters: {
                    mime_types : [ //只允许上传图片和zip文件
                        { title : "Image files", extensions : "jpg,gif,png,bmp,jpeg" }
                        // , { title : "Zip files", extensions : "zip,rar" }
                    ],
                    max_file_size : '10mb', //最大只能上传10mb的文件
                    prevent_duplicates : false //允许选取重复文件
                },

                init: {
                    PostInit: function() {
                        document.getElementById('ossfile').innerHTML = '';
                        //document.getElementById('postfiles').onclick = function() {
                        //    set_upload_param(uploader, '', false);
                        //    return false;
                        //};

                    },

                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                                    +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                                    +'</div>';
                            }
                        );
                        set_upload_param(uploader, '', false);
                    },

                    BeforeUpload: function(up, file) {
                        check_object_radio();
                        set_upload_param(up, file.name, true);
                    },

                    UploadProgress: function(up, file) {
                        var d = document.getElementById(file.id);
                        d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        var prog = d.getElementsByTagName('div')[0];
                        var progBar = prog.getElementsByTagName('div')[0];
                        progBar.style.width= 2*file.percent+'px';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function(up, file, info) {
                        // if (info.status == 200) {
                        //     document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name) + ' 回调服务器返回的内容是:' + info.response;
                        // } else if (info.status == 203) {
                        //     document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response;
                        // } else {
                        //     document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                        // }
                        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功';
                        //console.info("上传成功"+file.name);
                        var str = '<img src="' + host + '/' + get_uploaded_object_name(file.name) +'" />';
                       if(previewId != '#avatar')
                        $(previewId).append(str);    //添加图片预览
                        $('#'+file.id).remove();    //移除已上传完成的进度条

                        /*客服发送消息  上传图片成功之后直接发送消息*/






                        //修改头像
                        //if(previewId=='#avatar'){
                        //    $timeout(function(){
                        //        var avatar = host + '/' + get_uploaded_object_name(file.name);
                        //        var user = ipCookie('user');
                        //        user.avatar = avatar;
                        //        ipCookie('user',user,ipCookiesParam)
                        //        ipCookie('avatar', avatar, ipCookiesParam);
                        //        $rootScope.avatar = avatar;
                        //    $fetch.fetch(
                        //        '/user/editUserInfo',
                        //        {
                        //            params: {
                        //                id:ipCookie('Uid'),
                        //                avatar:avatar
                        //            }
                        //        }
                        //    ).then(function(data){
                        //
                        //        }).catch(function(e){
                        //            alert(e.msg);
                        //        })
                        //    })
                        //
                        //}
                    },

                    Error: function(up, err) {
                        if (err.code == -600) {
                            modalService.mainMsgInfo("选择的文件太大了,最大只能上传10mb的文件.");
                            //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,最大只能上传10mb的文件."));
                        } else if (err.code == -601) {
                            modalService.mainMsgInfo("选择的文件后缀不对,只允许上传图片.");
                            //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,只允许上传图片."));
                        } else if (err.code == -602) {
                            modalService.mainMsgInfo("你刚上传了这个，换一张吧!");
                            //document.getElementById('console').appendChild(document.createTextNode("\n该文件已上传."));
                        } else {
                            modalService.mainMsgInfo("上传失败!");
                        }
                    }
                }
            });

            uploader.init();
        }
    }
}]);







//ekt.service('Util', function($q) {
//    var dataURItoBlob = function(dataURI) {
//        // convert base64/URLEncoded data component to raw binary data held in a string
//        var byteString;
//        if (dataURI.split(',')[0].indexOf('base64') >= 0)
//            byteString = atob(dataURI.split(',')[1]);
//        else
//            byteString = unescape(dataURI.split(',')[1]);
//
//        // separate out the mime component
//        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
//
//        // write the bytes of the string to a typed array
//        var ia = new Uint8Array(byteString.length);
//        for (var i = 0; i < byteString.length; i++) {
//            ia[i] = byteString.charCodeAt(i);
//        }
//
//        return new Blob([ia], {
//            type: mimeString
//        });
//    };
//
//    var resizeFile = function(file) {
//        console.info(2146565);
//        var deferred = $q.defer();
//        var img = document.createElement("img");
//        try {
//            var reader = new FileReader();
//            reader.onload = function(e) {
//                img.src = e.target.result;
//
//                //resize the image using canvas
//                var canvas = document.createElement("canvas");
//                var ctx = canvas.getContext("2d");
//                ctx.drawImage(img, 0, 0);
//                var MAX_WIDTH = 800;
//                var MAX_HEIGHT = 800;
//                var width = img.width;
//                var height = img.height;
//                if (width > height) {
//                    if (width > MAX_WIDTH) {
//                        height *= MAX_WIDTH / width;
//                        width = MAX_WIDTH;
//                    }
//                } else {
//                    if (height > MAX_HEIGHT) {
//                        width *= MAX_HEIGHT / height;
//                        height = MAX_HEIGHT;
//                    }
//                }
//                canvas.width = width;
//                canvas.height = height;
//                var ctx = canvas.getContext("2d");
//                ctx.drawImage(img, 0, 0, width, height);
//
//                //change the dataUrl to blob data for uploading to server
//                var dataURL = canvas.toDataURL('image/jpeg');
//                var blob = dataURItoBlob(dataURL);
//
//                deferred.resolve(blob);
//            };
//            reader.readAsDataURL(file);
//        } catch (e) {
//            deferred.resolve(e);
//        }
//        return deferred.promise;
//
//    };
//    return {
//        resizeFile: resizeFile
//    };
//
//});